import React, { useEffect, useRef, useState } from 'react'

const ChineseLoadingAnimation = ({ isVisible, message = "诗意生成中..." }) => {
  const canvasRef = useRef(null)
  const animationRef = useRef(null)
  const [contextLost, setContextLost] = useState(false)

  useEffect(() => {
    if (!isVisible || !canvasRef.current || contextLost) return

    const canvas = canvasRef.current
    const gl = canvas.getContext('webgl')
    
    if (!gl) {
      console.warn('WebGL not supported, falling back to 2D canvas')
      return render2DFallback()
    }

    // WebGL上下文丢失处理
    const handleContextLost = (e) => {
      e.preventDefault()
      setContextLost(true)
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current)
      }
    }

    const handleContextRestored = () => {
      setContextLost(false)
    }

    canvas.addEventListener('webglcontextlost', handleContextLost)
    canvas.addEventListener('webglcontextrestored', handleContextRestored)

    // 设置canvas尺寸 - 确保正确的等比例缩放
    const resizeCanvas = () => {
      const rect = canvas.getBoundingClientRect()
      const size = Math.min(rect.width, rect.height) // 确保正方形
      const pixelRatio = Math.min(window.devicePixelRatio, 2) // 限制像素比，避免过度渲染
      
      canvas.width = size * pixelRatio
      canvas.height = size * pixelRatio
      gl.viewport(0, 0, canvas.width, canvas.height)
      
      // 确保canvas显示尺寸与实际尺寸匹配
      canvas.style.width = size + 'px'
      canvas.style.height = size + 'px'
    }

    resizeCanvas()
    window.addEventListener('resize', resizeCanvas)

    // 着色器源码
    const vertexShaderSource = `
      attribute vec2 a_position;
      uniform float u_time;
      uniform vec2 u_resolution;
      varying vec2 v_pos;
      
      void main() {
        v_pos = a_position;
        gl_Position = vec4(a_position, 0.0, 1.0);
      }
    `

    const fragmentShaderSource = `
      precision mediump float;
      uniform float u_time;
      uniform vec2 u_resolution;
      varying vec2 v_pos;
      
      // 生成噪声函数
      float noise(vec2 st) {
        return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
      }
      
      // 水墨扩散效果
      float inkDiffusion(vec2 uv, float time) {
        vec2 center = vec2(0.0, 0.0);
        float dist = length(uv - center);
        
        // 创建多层扩散波纹
        float wave1 = sin(dist * 8.0 - time * 3.0) * 0.5 + 0.5;
        float wave2 = sin(dist * 12.0 - time * 2.0) * 0.3 + 0.7;
        float wave3 = sin(dist * 16.0 - time * 4.0) * 0.2 + 0.8;
        
        return wave1 * wave2 * wave3;
      }
      
      // 飘落的花瓣效果
      float petals(vec2 uv, float time) {
        float petal = 0.0;
        for(int i = 0; i < 5; i++) {
          float fi = float(i);
          vec2 pos = vec2(
            sin(time * 0.8 + fi * 1.5) * 0.6,
            cos(time * 0.6 + fi * 2.0) * 0.4 - time * 0.3 + fi * 0.8
          );
          pos.y = mod(pos.y + 2.0, 4.0) - 2.0;
          
          float dist = length(uv - pos);
          petal += smoothstep(0.15, 0.05, dist) * (0.5 + 0.5 * sin(time + fi));
        }
        return petal;
      }
      
      // 古风色彩
      vec3 ancientColors(float t) {
        vec3 color1 = vec3(0.8, 0.7, 0.5);  // 宣纸色
        vec3 color2 = vec3(0.6, 0.4, 0.3);  // 棕墨色
        vec3 color3 = vec3(0.4, 0.2, 0.1);  // 深墨色
        
        return mix(mix(color1, color2, smoothstep(0.0, 0.5, t)), color3, smoothstep(0.5, 1.0, t));
      }
      
      void main() {
        vec2 uv = v_pos * 0.5 + 0.5;
        uv.x *= u_resolution.x / u_resolution.y;
        
        // 水墨扩散
        float ink = inkDiffusion(v_pos, u_time);
        
        // 飘落花瓣
        float petalEffect = petals(v_pos, u_time);
        
        // 噪声纹理
        float noiseValue = noise(uv * 10.0 + u_time * 0.1);
        
        // 组合效果
        float combined = ink * 0.6 + petalEffect * 0.3 + noiseValue * 0.1;
        
        // 应用古风色彩
        vec3 color = ancientColors(combined);
        
        // 中心渐变
        float centerGradient = 1.0 - smoothstep(0.0, 1.2, length(v_pos));
        color *= centerGradient * 0.7 + 0.3;
        
        gl_FragColor = vec4(color, combined * 0.8);
      }
    `

    // 创建着色器
    const createShader = (type, source) => {
      const shader = gl.createShader(type)
      gl.shaderSource(shader, source)
      gl.compileShader(shader)
      
      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        console.error('Shader compilation error:', gl.getShaderInfoLog(shader))
        gl.deleteShader(shader)
        return null
      }
      return shader
    }

    const vertexShader = createShader(gl.VERTEX_SHADER, vertexShaderSource)
    const fragmentShader = createShader(gl.FRAGMENT_SHADER, fragmentShaderSource)

    if (!vertexShader || !fragmentShader) {
      return render2DFallback()
    }

    // 创建程序
    const program = gl.createProgram()
    gl.attachShader(program, vertexShader)
    gl.attachShader(program, fragmentShader)
    gl.linkProgram(program)

    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      console.error('Program linking error:', gl.getProgramInfoLog(program))
      return render2DFallback()
    }

    // 获取位置和uniform
    const positionLocation = gl.getAttribLocation(program, 'a_position')
    const timeLocation = gl.getUniformLocation(program, 'u_time')
    const resolutionLocation = gl.getUniformLocation(program, 'u_resolution')

    // 创建缓冲区
    const positionBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
      -1, -1,  1, -1,  -1, 1,
      -1, 1,   1, -1,   1, 1
    ]), gl.STATIC_DRAW)

    // 渲染循环
    const startTime = Date.now()
    const render = () => {
      if (contextLost || !isVisible) return

      const currentTime = (Date.now() - startTime) / 1000

      // 清除画布
      gl.clearColor(0, 0, 0, 0)
      gl.clear(gl.COLOR_BUFFER_BIT)

      // 启用混合
      gl.enable(gl.BLEND)
      gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

      // 使用程序
      gl.useProgram(program)

      // 设置uniform
      gl.uniform1f(timeLocation, currentTime)
      gl.uniform2f(resolutionLocation, canvas.width, canvas.height)

      // 绑定位置属性
      gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
      gl.enableVertexAttribArray(positionLocation)
      gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)

      // 绘制
      gl.drawArrays(gl.TRIANGLES, 0, 6)

      animationRef.current = requestAnimationFrame(render)
    }

    render()

    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current)
      }
      canvas.removeEventListener('webglcontextlost', handleContextLost)
      canvas.removeEventListener('webglcontextrestored', handleContextRestored)
      window.removeEventListener('resize', resizeCanvas)
      
      if (gl && !contextLost) {
        gl.deleteProgram(program)
        gl.deleteShader(vertexShader)
        gl.deleteShader(fragmentShader)
        gl.deleteBuffer(positionBuffer)
      }
    }

    // 2D Canvas降级版本
    function render2DFallback() {
      const ctx = canvas.getContext('2d')
      let startTime = Date.now()

      const draw2D = () => {
        if (!isVisible) return

        const time = (Date.now() - startTime) / 1000
        const width = canvas.width
        const height = canvas.height

        // 清除画布
        ctx.clearRect(0, 0, width, height)

        // 设置样式
        ctx.globalAlpha = 0.6

        // 绘制水墨扩散圆圈 - 根据canvas尺寸等比例缩放
        const scale = width / 400; // 以400px为基准尺寸
        for (let i = 0; i < 5; i++) {
          const radius = (80 + i * 40 + Math.sin(time + i) * 25) * scale
          const alpha = 0.4 - i * 0.08
          
          const gradient = ctx.createRadialGradient(
            width/2, height/2, 0,
            width/2, height/2, radius
          )
          gradient.addColorStop(0, `rgba(139, 92, 70, ${alpha})`)
          gradient.addColorStop(0.6, `rgba(101, 67, 33, ${alpha * 0.6})`)
          gradient.addColorStop(1, 'rgba(101, 67, 33, 0)')

          ctx.fillStyle = gradient
          ctx.beginPath()
          ctx.arc(width/2, height/2, radius, 0, Math.PI * 2)
          ctx.fill()
        }

        // 绘制飘落元素 - 增加数量和等比例缩放
        for (let i = 0; i < 12; i++) {
          const x = width/2 + Math.sin(time * 0.5 + i) * (120 * scale)
          const y = (height/2 + Math.cos(time * 0.3 + i) * (80 * scale) + time * 40 * scale) % (height + 30 * scale) - 15 * scale
          const particleSize = (4 + Math.sin(time + i) * 2) * scale

          ctx.fillStyle = `rgba(139, 92, 70, ${0.5 + Math.sin(time + i) * 0.3})`
          ctx.beginPath()
          ctx.arc(x, y, particleSize, 0, Math.PI * 2)
          ctx.fill()
        }

        animationRef.current = requestAnimationFrame(draw2D)
      }

      draw2D()
      
      return () => {
        if (animationRef.current) {
          cancelAnimationFrame(animationRef.current)
        }
      }
    }

  }, [isVisible, contextLost])

  if (!isVisible) return null

  return (
    <div className="fixed inset-0 z-30 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm">
      {/* WebGL Canvas */}
      <div className="relative flex items-center justify-center">
        <canvas
          ref={canvasRef}
          className="rounded-full"
          style={{
            width: '400px',
            height: '400px',
            maxWidth: '90vmin',
            maxHeight: '90vmin',
            aspectRatio: '1 / 1',
            filter: 'drop-shadow(0 16px 64px rgba(139, 92, 70, 0.5))'
          }}
        />
        
        {/* 中心文字 */}
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <div className="text-2xl font-chinese text-white mb-4 animate-pulse">
            {message}
          </div>
          
          {/* 古风装饰 */}
          <div className="flex items-center space-x-2 text-white opacity-70">
            <div className="w-8 h-px bg-gradient-to-r from-transparent via-white to-transparent"></div>
            <div className="text-sm">墨香阵阵</div>
            <div className="w-8 h-px bg-gradient-to-r from-transparent via-white to-transparent"></div>
          </div>
        </div>
      </div>
      
      {/* 环绕粒子 - 优化轨道收敛性 */}
      <div
        className="absolute overflow-hidden pointer-events-none"
        style={{
          width: '450px',
          height: '450px',
          left: '50%',
          top: '50%',
          transform: 'translate(-50%, -50%)'
        }}
      >
        {[...Array(16)].map((_, i) => {
          const layer = i % 2; // 只有2层轨道，更集中
          const radius = 160 + layer * 25; // 更紧凑的轨道半径
          const speed = 12 - layer * 2; // 内层更快，外层稍慢
          return (
            <div
              key={i}
              className="absolute w-2 h-2 bg-gradient-to-r from-amber-400 to-gold-500 rounded-full shadow-md transition-opacity duration-1000"
              style={{
                left: '50%',
                top: '50%',
                opacity: 0.7,
                animation: `orbit-${layer} ${speed}s linear infinite`,
                transformOrigin: `0 0`,
                animationDelay: `${i * 0.4}s`
              }}
            />
          );
        })}
      </div>

      <style jsx>{`
        @keyframes orbit-0 {
          from {
            transform: rotate(0deg) translateX(160px) translateY(-1px);
          }
          to {
            transform: rotate(360deg) translateX(160px) translateY(-1px);
          }
        }
        @keyframes orbit-1 {
          from {
            transform: rotate(0deg) translateX(185px) translateY(-1px);
          }
          to {
            transform: rotate(360deg) translateX(185px) translateY(-1px);
          }
        }
        
        @keyframes fadeInScale {
          from {
            opacity: 0;
            transform: scale(0.8);
          }
          to {
            opacity: 1;
            transform: scale(1);
          }
        }
        
        @keyframes fadeOutScale {
          from {
            opacity: 1;
            transform: scale(1);
          }
          to {
            opacity: 0;
            transform: scale(0.85);
          }
        }
        
        @keyframes canvasAppear {
          from {
            opacity: 0;
            transform: scale(0.9) rotate(-5deg);
          }
          to {
            opacity: 1;
            transform: scale(1) rotate(0deg);
          }
        }
      `}</style>
    </div>
  )
}

export default ChineseLoadingAnimation